<template>
  <div>
    <nav-bar></nav-bar>
    <!-- 分割线 -->
    <van-divider dashed :style="{ color: '#1a73e8', borderColor: '#1a73e8', padding: '0 16px' }">现有栏目</van-divider>
    <div class="new_category">
      <p v-for="item in newCat" :key="item._id" @click="handleClickDel(item._id)">{{item.title}}</p>
    </div>
    <van-divider dashed :style="{ color: '#ee0a24', borderColor: '#ee0a24', padding: '0 16px' }">已删除栏目</van-divider>
    <div class="new_category del_category">
      <p v-for="item in delCat" :key="item._id" @click="handleClickAdd(item._id)">{{item.title}}</p>
    </div>
  </div>
</template>

<script>
import NavBar from '../components/common/NavBar.vue'
export default {
  data () {
    return {
      newCat: [],
      delCat: []
    }
  },
  created () {
    if (localStorage.getItem('newCat') && localStorage.getItem('delCat')) {
      this.newCat = JSON.parse(localStorage.getItem('newCat'))
      this.delCat = JSON.parse(localStorage.getItem('delCat'))
      return
    }
    this.getCategory()
  },
  methods: {
    // 获取导航数据
    async getCategory () {
      const res = await this.$http.get('/category')
      if (res.status !== 200) return this.$msg.fail('获取导航数据失败')
      this.newCat = res.data
    },
    handleClickDel (id) {
      if (this.newCat.length < 4) {
        return this.$msg.fail('最少保留三个栏目')
      }
      const idx = this.newCat.findIndex(item => {
        return item._id === id
      })
      const res = this.newCat.splice(idx, 1)
      this.delCat.push(res[0])
    },
    handleClickAdd (id) {
      const idx = this.delCat.findIndex(item => {
        return item._id === id
      })
      const res = this.delCat.splice(idx, 1)
      this.newCat.push(res[0])
    }
  },
  watch: {
    // 监听数组变化,缓存到本地
    newCat () {
      localStorage.setItem('newCat', JSON.stringify(this.newCat))
      localStorage.setItem('delCat', JSON.stringify(this.delCat))
    }
  },
  components: {
    NavBar
  }
}
</script>

<style lang="less" scoped>
.new_category {
  padding: 0 2.778vw;
  display: flex;
  flex-wrap: wrap;
  p {
    width: 20%;
    padding: 1.389vw 0;
    border: 1px solid #1a73e8;
    margin: 1.944vw 1.944vw;
    text-align: center;
    font-size: 15px;
    color: #1a73e8;
  }
}
.del_category {
  p {
    border: 1px solid #ee0a24;
    color: #ee0a24;
  }
}
</style>
